# -*- coding: utf-8 -*-
from os import path
import sqlite3
from PyQt5.QtWidgets import QTabWidget, QWidget, QHBoxLayout, QTreeView, QLineEdit, QTreeWidget, QTreeWidgetItem
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QIcon, QPixmap
from queryform import QueryForm
from treemodel import TreeModel

class TabWindow(QWidget):
    queryname = '查询'

    def __init__(self, parent=None):
        super(TabWindow, self).__init__(parent)

        self.queryIndex = 0

        self.tab = QTabWidget()
        self.tab.setTabsClosable(True)
        self.tab.tabCloseRequested.connect(self.closeTab)

        # self.treeModel = TreeModel(data=['Hello',])

        # self.tree = QTreeView()
        # self.tree.setMaximumWidth(200)
        # self.tree.setModel(self.treeModel)
        self.tree = QTreeWidget()
        self.tree.setMaximumWidth(200)
        self.tree.setHeaderLabel('导航')
        self.tree.setColumnCount(1)

        main = QHBoxLayout()
        main.addWidget(self.tree)
        main.addWidget(self.tab)
        self.setLayout(main)
        self.databases = {}

    @pyqtSlot(str)
    def setOpen(self, filename):
        basename = path.basename(filename)
        connection = sqlite3.Connection(filename)
        self.databases[basename] = connection

        newForm = QueryForm(connection)
        item = QTreeWidgetItem(self.tree)
        item.setText(0, basename)
        self.tree.insertTopLevelItems(0, [item])

        self.loadDetail(item, connection)

        index = self.tab.addTab(newForm, self.setQueryName(basename))
        self.tab.setCurrentIndex(index)

    @pyqtSlot(int)
    def closeTab(self, index):
        self.tab.removeTab(index)

    @pyqtSlot()
    def executeQuery(self):
        self.tab.currentWidget().execute()

    @pyqtSlot()
    def closeConnection(self):
        print('Current connection will be closed')

    @pyqtSlot()
    def openQuery(self):
        name = self.tree.currentItem().text(0)
        form = QueryForm(self.databases[name])
        index = self.tab.addTab(form, self.setQueryName(name))
        self.tab.setCurrentIndex(index)

    def setQueryName(self, dbName):
        self.queryIndex += 1
        return '查询%d - %s' % (self.queryIndex, dbName)

    def loadDetail(self, item, connection):
        table = QTreeWidgetItem(item)
        table.setText(0, '表')
        item.addChild(table)
        sql = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"
        cursor = connection.execute(sql)
        for row in cursor.fetchall():
            child = QTreeWidgetItem(table)
            child.setText(0, row[0])
            table.addChild(child)
        cursor.close()
